{% extends "base.html" %}

{% block title %}个人课程表{% endblock %}

{% block extra_css %}
<style>
    .schedule-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 2rem 0;
        border-radius: 0 0 1rem 1rem;
        margin-bottom: 2rem;
    }

    .view-toggle {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 0.5rem;
        padding: 0.25rem;
    }

    .view-toggle .btn {
        border: none;
        color: rgba(255, 255, 255, 0.8);
        background: transparent;
    }

    .view-toggle .btn.active {
        background: rgba(255, 255, 255, 0.2);
        color: white;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
    }

    .schedule-stats {
        background: rgba(255, 255, 255, 0.1);
        border-radius: 0.75rem;
        padding: 1.5rem;
        backdrop-filter: blur(10px);
    }

    .stat-item {
        text-align: center;
        color: white;
    }

    .stat-number {
        font-size: 2rem;
        font-weight: bold;
        display: block;
    }

    .stat-label {
        font-size: 0.875rem;
        opacity: 0.9;
    }

    .schedule-container {
        background: white;
        border-radius: 1rem;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        overflow: hidden;
    }

    .time-navigation {
        background: #f8f9fa;
        padding: 1rem;
        border-bottom: 1px solid #e9ecef;
    }

    .week-view .time-slot {
        height: 60px;
        border-bottom: 1px solid #e9ecef;
        position: relative;
    }

    .week-view .time-label {
        width: 80px;
        background: #f8f9fa;
        border-right: 1px solid #e9ecef;
        font-size: 0.875rem;
        color: #6c757d;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .week-view .day-column {
        flex: 1;
        border-right: 1px solid #e9ecef;
        position: relative;
    }

    .week-view .day-column:last-child {
        border-right: none;
    }

    .week-view .day-header {
        background: #667eea;
        color: white;
        padding: 0.75rem;
        text-align: center;
        font-weight: 500;
    }

    .week-view .day-header.today {
        background: #28a745;
    }

    .reservation-block {
        position: absolute;
        left: 2px;
        right: 2px;
        background: linear-gradient(135deg, #667eea, #764ba2);
        color: white;
        border-radius: 0.25rem;
        padding: 0.25rem 0.5rem;
        font-size: 0.75rem;
        cursor: pointer;
        transition: all 0.3s ease;
        z-index: 10;
    }

    .reservation-block:hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    }

    .reservation-block.confirmed {
        background: linear-gradient(135deg, #28a745, #20c997);
    }

    .reservation-block.pending {
        background: linear-gradient(135deg, #ffc107, #fd7e14);
    }

    .reservation-block.completed {
        background: linear-gradient(135deg, #6c757d, #495057);
    }

    .day-view .day-schedule {
        min-height: 600px;
    }

    .day-view .time-slot {
        height: 80px;
        border-bottom: 1px solid #e9ecef;
        display: flex;
    }

    .day-view .reservation-card {
        background: white;
        border: 1px solid #e9ecef;
        border-radius: 0.5rem;
        padding: 1rem;
        margin: 0.5rem;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        cursor: pointer;
        transition: all 0.3s ease;
    }

    .day-view .reservation-card:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
    }

    .reservation-card .status-badge {
        font-size: 0.75rem;
        padding: 0.25rem 0.5rem;
        border-radius: 0.25rem;
        font-weight: 500;
    }

    .reservation-card .student-name {
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 0.25rem;
    }

    .reservation-card .time-info {
        color: #6c757d;
        font-size: 0.875rem;
    }

    .reservation-card .table-info {
        color: #007bff;
        font-size: 0.875rem;
        font-weight: 500;
    }

    .empty-slot {
        color: #6c757d;
        font-style: italic;
        padding: 1rem;
        text-align: center;
    }

    .quick-actions {
        position: fixed;
        bottom: 2rem;
        right: 2rem;
        z-index: 1000;
    }

    .quick-actions .btn {
        border-radius: 50%;
        width: 56px;
        height: 56px;
        margin-bottom: 0.5rem;
        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
    }

    @media (max-width: 768px) {
        .schedule-header {
            padding: 1rem 0;
        }

        .week-view {
            display: none;
        }

        .mobile-day-view {
            display: block !important;
        }

        .reservation-block {
            font-size: 0.7rem;
            padding: 0.1rem 0.25rem;
        }

        .quick-actions {
            bottom: 1rem;
            right: 1rem;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="schedule-header">
    <div class="container">
        <div class="row align-items-center">
            <div class="col-md-6">
                <h1 class="mb-0">
                    <i class="fas fa-calendar-alt me-2"></i>个人课程表
                </h1>
                <p class="mb-0 mt-2 opacity-75">管理您的教学安排</p>
            </div>
            <div class="col-md-6">
                <div class="row">
                    <div class="col-md-6">
                        <div class="view-toggle btn-group">
                            <button type="button" class="btn btn-sm active" data-view="week">
                                <i class="fas fa-th me-1"></i>周视图
                            </button>
                            <button type="button" class="btn btn-sm" data-view="day">
                                <i class="fas fa-list me-1"></i>日视图
                            </button>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="schedule-stats">
                            <div class="stat-item">
                                <span class="stat-number">{{ today_count }}</span>
                                <span class="stat-label">今日课程</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid">
    <div class="schedule-container">
        <!-- 时间导航 -->
        <div class="time-navigation">
            <div class="row align-items-center">
                <div class="col-md-4">
                    <div class="btn-group">
                        <button type="button" class="btn btn-outline-primary btn-sm" id="prevPeriod">
                            <i class="fas fa-chevron-left"></i>
                        </button>
                        <button type="button" class="btn btn-outline-primary btn-sm" id="todayBtn">今天</button>
                        <button type="button" class="btn btn-outline-primary btn-sm" id="nextPeriod">
                            <i class="fas fa-chevron-right"></i>
                        </button>
                    </div>
                </div>
                <div class="col-md-4 text-center">
                    <h5 class="mb-0" id="currentPeriod">
                        {% if view_type == 'week' %}
                            {{ current_week_start.strftime('%Y年%m月%d日') }} - {{ current_week_end.strftime('%m月%d日') }}
                        {% else %}
                            {{ current_date.strftime('%Y年%m月%d日 %A') }}
                        {% endif %}
                    </h5>
                </div>
                <div class="col-md-4 text-end">
                    <button type="button" class="btn btn-sm btn-outline-info" onclick="refreshSchedule()" title="刷新">
                        <i class="fas fa-sync-alt"></i>
                    </button>
                </div>
            </div>
        </div>

        <!-- 周视图 -->
        <div class="week-view" {% if view_type == 'day' %}style="display: none;"{% endif %}>
            <!-- 星期标题行 -->
            <div class="d-flex">
                <div class="time-label"></div>
                {% for day_info in week_days %}
                <div class="day-column">
                    <div class="day-header {% if day_info.is_today %}today{% endif %}">
                        <div>{{ day_info.weekday }}</div>
                        <div>{{ day_info.date.strftime('%m/%d') }}</div>
                    </div>
                </div>
                {% endfor %}
            </div>

            <!-- 时间槽 -->
            {% for hour in range(8, 22) %}
            <div class="d-flex time-slot">
                <div class="time-label">{{ '%02d:00'|format(hour) }}</div>
                {% for day_info in week_days %}
                <div class="day-column" data-date="{{ day_info.date.strftime('%Y-%m-%d') }}" data-hour="{{ hour }}">
                    {% for reservation in day_info.reservations %}
                        {% if reservation.start_time.hour == hour %}
                        <div class="reservation-block {{ reservation.status }}"
                             style="top: {{ ((reservation.start_time.minute / 60) * 60)|int }}px;
                                    height: {{ ((reservation.duration_minutes / 60) * 60)|int }}px;"
                             data-reservation-id="{{ reservation.id }}"
                             title="{{ reservation.student.name }} - {{ reservation.start_time.strftime('%H:%M') }}-{{ reservation.end_time.strftime('%H:%M') }}">
                            <div class="fw-bold">{{ reservation.student.name }}</div>
                            <div>{{ reservation.start_time.strftime('%H:%M') }}-{{ reservation.end_time.strftime('%H:%M') }}</div>
                            <div>{{ reservation.table.name }}</div>
                        </div>
                        {% endif %}
                    {% endfor %}
                </div>
                {% endfor %}
            </div>
            {% endfor %}
        </div>

        <!-- 日视图 -->
        <div class="day-view" {% if view_type == 'week' %}style="display: none;"{% endif %}>
            <div class="day-schedule">
                {% if daily_reservations %}
                    {% for reservation in daily_reservations %}
                    <div class="reservation-card" data-reservation-id="{{ reservation.id }}">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <div class="student-name">{{ reservation.student.name }}</div>
                            <span class="status-badge bg-{{ reservation.status_color }}">
                                {{ reservation.status_text }}
                            </span>
                        </div>
                        <div class="row">
                            <div class="col-md-4">
                                <div class="time-info">
                                    <i class="fas fa-clock me-1"></i>
                                    {{ reservation.start_time.strftime('%H:%M') }} - {{ reservation.end_time.strftime('%H:%M') }}
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="table-info">
                                    <i class="fas fa-table-tennis me-1"></i>
                                    {{ reservation.table.name }}
                                </div>
                            </div>
                            <div class="col-md-4 text-end">
                                <div class="btn-group btn-group-sm">
                                    {% if reservation.status == 'pending' %}
                                    <button type="button" class="btn btn-outline-success btn-sm"
                                            onclick="confirmReservation({{ reservation.id }})">
                                        <i class="fas fa-check"></i>确认
                                    </button>
                                    <button type="button" class="btn btn-outline-danger btn-sm"
                                            onclick="rejectReservation({{ reservation.id }})">
                                        <i class="fas fa-times"></i>拒绝
                                    </button>
                                    {% elif reservation.status == 'confirmed' %}
                                    <button type="button" class="btn btn-outline-primary btn-sm"
                                            onclick="viewReservation({{ reservation.id }})">
                                        <i class="fas fa-eye"></i>详情
                                    </button>
                                    <button type="button" class="btn btn-outline-success btn-sm"
                                            onclick="completeReservation({{ reservation.id }})">
                                        <i class="fas fa-check-circle"></i>完成
                                    </button>
                                    {% else %}
                                    <button type="button" class="btn btn-outline-info btn-sm"
                                            onclick="viewReservation({{ reservation.id }})">
                                        <i class="fas fa-eye"></i>详情
                                    </button>
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                        {% if reservation.notes %}
                        <div class="mt-2">
                            <small class="text-muted">
                                <i class="fas fa-sticky-note me-1"></i>{{ reservation.notes }}
                            </small>
                        </div>
                        {% endif %}
                    </div>
                    {% endfor %}
                {% else %}
                    <div class="empty-slot">
                        <i class="fas fa-calendar-times fa-3x mb-3 text-muted"></i>
                        <p>今天没有安排课程</p>
                        <a href="{{ url_for('coach_reservations.pending') }}" class="btn btn-outline-primary">
                            查看待处理预约
                        </a>
                    </div>
                {% endif %}
            </div>
        </div>

        <!-- 移动端日视图 -->
        <div class="mobile-day-view d-md-none" style="display: none;">
            {% for reservation in daily_reservations %}
            <div class="card mb-2">
                <div class="card-body py-2">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <strong>{{ reservation.student.name }}</strong>
                            <br>
                            <small class="text-muted">
                                {{ reservation.start_time.strftime('%H:%M') }}-{{ reservation.end_time.strftime('%H:%M') }} | {{ reservation.table.name }}
                            </small>
                        </div>
                        <span class="badge bg-{{ reservation.status_color }}">
                            {{ reservation.status_text }}
                        </span>
                    </div>
                </div>
            </div>
            {% endfor %}
        </div>
    </div>
</div>

<!-- 快捷操作 -->
<div class="quick-actions">
    <button type="button" class="btn btn-primary" onclick="location.href='{{ url_for('coach_reservations.pending') }}'" title="待处理预约">
        <i class="fas fa-clock"></i>
    </button>
    <button type="button" class="btn btn-success" onclick="refreshSchedule()" title="刷新课程表">
        <i class="fas fa-sync-alt"></i>
    </button>
</div>

<!-- 预约详情模态框 -->
<div class="modal fade" id="reservationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">预约详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="reservationModalBody">
                <!-- 动态加载内容 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    let currentView = 'week';
    let currentDate = new Date('{{ current_date.strftime("%Y-%m-%d") }}');

    // 视图切换
    $('.view-toggle .btn').click(function() {
        $('.view-toggle .btn').removeClass('active');
        $(this).addClass('active');

        const view = $(this).data('view');
        currentView = view;

        if (view === 'week') {
            $('.week-view').show();
            $('.day-view').hide();
        } else {
            $('.week-view').hide();
            $('.day-view').show();
        }

        loadScheduleData();
    });

    // 时间导航
    $('#prevPeriod').click(function() {
        if (currentView === 'week') {
            currentDate.setDate(currentDate.getDate() - 7);
        } else {
            currentDate.setDate(currentDate.getDate() - 1);
        }
        loadScheduleData();
    });

    $('#nextPeriod').click(function() {
        if (currentView === 'week') {
            currentDate.setDate(currentDate.getDate() + 7);
        } else {
            currentDate.setDate(currentDate.getDate() + 1);
        }
        loadScheduleData();
    });

    $('#todayBtn').click(function() {
        currentDate = new Date();
        loadScheduleData();
    });

    // 预约块点击事件
    $(document).on('click', '.reservation-block, .reservation-card', function() {
        const reservationId = $(this).data('reservation-id');
        viewReservation(reservationId);
    });

    // 加载课程表数据
    function loadScheduleData() {
        const dateStr = currentDate.toISOString().split('T')[0];
        const url = `{{ url_for('coach_reservations.schedule') }}?date=${dateStr}&view=${currentView}`;

        $.get(url, function(response) {
            if (response.success) {
                updateScheduleDisplay(response.data);
            } else {
                showAlert('error', response.message || '加载课程表失败');
            }
        }).fail(function() {
            showAlert('error', '网络错误，请重试');
        });
    }

    // 更新课程表显示
    function updateScheduleDisplay(data) {
        $('#currentPeriod').text(data.period_text);

        if (currentView === 'week') {
            updateWeekView(data.schedule);
        } else {
            updateDayView(data.schedule);
        }
    }

    // 更新周视图
    function updateWeekView(schedule) {
        $('.day-column[data-date]').each(function() {
            const date = $(this).data('date');
            const hour = $(this).data('hour');

            $(this).find('.reservation-block').remove();

            if (schedule[date]) {
                schedule[date].forEach(function(reservation) {
                    if (reservation.start_hour === hour) {
                        const block = createReservationBlock(reservation);
                        $(this).append(block);
                    }
                });
            }
        });
    }

    // 更新日视图
    function updateDayView(schedule) {
        const container = $('.day-schedule');
        container.empty();

        const dateStr = currentDate.toISOString().split('T')[0];
        const reservations = schedule[dateStr] || [];

        if (reservations.length === 0) {
            container.html(`
                <div class="empty-slot">
                    <i class="fas fa-calendar-times fa-3x mb-3 text-muted"></i>
                    <p>今天没有安排课程</p>
                    <a href="{{ url_for('coach_reservations.pending') }}" class="btn btn-outline-primary">
                        查看待处理预约
                    </a>
                </div>
            `);
        } else {
            reservations.forEach(function(reservation) {
                const card = createReservationCard(reservation);
                container.append(card);
            });
        }
    }

    // 创建预约块
    function createReservationBlock(reservation) {
        return `
            <div class="reservation-block ${reservation.status}"
                 data-reservation-id="${reservation.id}"
                 title="${reservation.student_name} - ${reservation.time_range}">
                <div class="fw-bold">${reservation.student_name}</div>
                <div>${reservation.time_range}</div>
                <div>${reservation.table_name}</div>
            </div>
        `;
    }

    // 创建预约卡片
    function createReservationCard(reservation) {
        let actionButtons = '';

        if (reservation.status === 'pending') {
            actionButtons = `
                <button type="button" class="btn btn-outline-success btn-sm"
                        onclick="confirmReservation(${reservation.id})">
                    <i class="fas fa-check"></i>确认
                </button>
                <button type="button" class="btn btn-outline-danger btn-sm"
                        onclick="rejectReservation(${reservation.id})">
                    <i class="fas fa-times"></i>拒绝
                </button>
            `;
        } else if (reservation.status === 'confirmed') {
            actionButtons = `
                <button type="button" class="btn btn-outline-primary btn-sm"
                        onclick="viewReservation(${reservation.id})">
                    <i class="fas fa-eye"></i>详情
                </button>
                <button type="button" class="btn btn-outline-success btn-sm"
                        onclick="completeReservation(${reservation.id})">
                    <i class="fas fa-check-circle"></i>完成
                </button>
            `;
        } else {
            actionButtons = `
                <button type="button" class="btn btn-outline-info btn-sm"
                        onclick="viewReservation(${reservation.id})">
                    <i class="fas fa-eye"></i>详情
                </button>
            `;
        }

        return `
            <div class="reservation-card" data-reservation-id="${reservation.id}">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <div class="student-name">${reservation.student_name}</div>
                    <span class="status-badge bg-${reservation.status_color}">
                        ${reservation.status_text}
                    </span>
                </div>
                <div class="row">
                    <div class="col-md-4">
                        <div class="time-info">
                            <i class="fas fa-clock me-1"></i>
                            ${reservation.time_range}
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="table-info">
                            <i class="fas fa-table-tennis me-1"></i>
                            ${reservation.table_name}
                        </div>
                    </div>
                    <div class="col-md-4 text-end">
                        <div class="btn-group btn-group-sm">
                            ${actionButtons}
                        </div>
                    </div>
                </div>
                ${reservation.notes ? `
                    <div class="mt-2">
                        <small class="text-muted">
                            <i class="fas fa-sticky-note me-1"></i>${reservation.notes}
                        </small>
                    </div>
                ` : ''}
            </div>
        `;
    }
});

// 查看预约详情
function viewReservation(reservationId) {
    $.ajax({
        url: `{{ url_for('coach_reservations.detail', reservation_id=0) }}`.replace('0', reservationId),
        type: 'GET',
        headers: {
            'X-Requested-With': 'XMLHttpRequest'
        },
        success: function(response) {
            if (response.success) {
                $('#reservationModalBody').html(response.html);
                $('#reservationModal').modal('show');
            } else {
                showAlert('error', response.message || '加载预约详情失败');
            }
        },
        error: function() {
            showAlert('error', '网络错误，请重试');
        }
    });
}

// 确认预约
function confirmReservation(reservationId) {
    if (!confirm('确定要确认这个预约吗？')) return;

    $.post(`{{ url_for('coach_reservations.api_confirm_reservation', reservation_id=0) }}`.replace('0', reservationId), function(response) {
        if (response.success) {
            showAlert('success', '预约已确认');
            $('#reservationModal').modal('hide');
            refreshSchedule();
        } else {
            showAlert('error', response.message || '确认预约失败');
        }
    }).fail(function() {
        showAlert('error', '网络错误，请重试');
    });
}

// 拒绝预约
function rejectReservation(reservationId) {
    const reason = prompt('请输入拒绝原因（选填）：');
    if (reason === null) return;

    $.post(`{{ url_for('coach_reservations.api_reject_reservation', reservation_id=0) }}`.replace('0', reservationId), {
        reason: reason
    }, function(response) {
        if (response.success) {
            showAlert('success', '预约已拒绝');
            $('#reservationModal').modal('hide');
            refreshSchedule();
        } else {
            showAlert('error', response.message || '拒绝预约失败');
        }
    }).fail(function() {
        showAlert('error', '网络错误，请重试');
    });
}

// 完成预约
function completeReservation(reservationId) {
    if (!confirm('确定要标记这个预约为已完成吗？')) return;

    $.post(`{{ url_for('coach_reservations.api_complete_reservation', reservation_id=0) }}`.replace('0', reservationId), function(response) {
        if (response.success) {
            showAlert('success', '预约已完成');
            $('#reservationModal').modal('hide');
            refreshSchedule();
        } else {
            showAlert('error', response.message || '完成预约失败');
        }
    }).fail(function() {
        showAlert('error', '网络错误，请重试');
    });
}

// 标记未出席
function markNoShow(reservationId) {
    if (!confirm('确定要标记此学员为未出席吗？')) return;

    $.post(`{{ url_for('coach_reservations.api_mark_no_show', reservation_id=0) }}`.replace('0', reservationId), function(response) {
        if (response.success) {
            showAlert('success', '已标记为未出席');
            $('#reservationModal').modal('hide');
            refreshSchedule();
        } else {
            showAlert('error', response.message || '标记失败');
        }
    }).fail(function() {
        showAlert('error', '网络错误，请重试');
    });
}

// 取消预约
function cancelReservation(reservationId) {
    const reason = prompt('请输入取消原因：');
    if (reason === null || reason.trim() === '') return;

    if (!confirm('确定要取消这个预约吗？')) return;

    $.post(`{{ url_for('coach_reservations.api_cancel_reservation', reservation_id=0) }}`.replace('0', reservationId), {
        reason: reason.trim()
    }, function(response) {
        if (response.success) {
            showAlert('success', '预约已取消');
            $('#reservationModal').modal('hide');
            refreshSchedule();
        } else {
            showAlert('error', response.message || '取消预约失败');
        }
    }).fail(function() {
        showAlert('error', '网络错误，请重试');
    });
}

// 刷新课程表
function refreshSchedule() {
    loadScheduleData();
}

// 显示提示信息
function showAlert(type, message) {
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    const icon = type === 'success' ? 'check-circle' : 'exclamation-triangle';

    const alert = $(`
        <div class="alert ${alertClass} alert-dismissible fade show position-fixed"
             style="top: 20px; right: 20px; z-index: 9999;">
            <i class="fas fa-${icon} me-2"></i>${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `);

    $('body').append(alert);

    setTimeout(function() {
        alert.alert('close');
    }, 3000);
}
</script>
{% endblock %}